<template>
    <div class="tables-main">  
      <div class="table-box">
        <div class="down-bth" v-if="userRole.level=='国家级'">
          <countryFile :reportItem="reportItem"/>
        </div>
        <el-table
          style="width: 90%;margin: 10px auto"
          :data="tableData"
           border
          :header-cell-style="{
            background: '#E7F2FF',
            color: 'black',
          }"
          v-loading="loading"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="val" label="期别" width="150" align="center"/>
          <el-table-column prop="templateType" label="报表类型" width="200" align="center"/>
          <el-table-column label="是否超时" width="200">
          <template #default="scope">
            {{ scope.row.notice? '已超时' : '未超时' }}
          </template>
          </el-table-column>
          <el-table-column prop="deadline" label="填报截至时间" width="180" align="center"/>
          <el-table-column prop="developArea" label="填报人" width="180" align="center"/>
          <el-table-column prop="checkTime" label="审核时间" width="180" align="center"/>
          <el-table-column prop="reportTime" label="上报时间" width="180" align="center"/>
          <el-table-column label="操作" min-width="280" width="auto" fixed="right" align="center">
            <template #default="scope">
              <el-button v-if="userRole.level!='国家级'" link type="primary" size="small" @click="getEdit(scope.row,'first')">{{scope.row.tstate == '2'?'编辑':'填报'}}</el-button>   
              <el-button v-if="scope.row.tstate == '2'" link type="primary" size="small" @click="getReport(scope.row)">上报</el-button>
              <el-button v-if="userRole.level!='国家级'" link type="primary" size="small" @click="downReport(scope.row)">导出</el-button>
              <el-button v-if="userRole.level=='国家级'" link type="primary" size="small" @click="downReports(scope.row)">报表导出</el-button>
              <el-button v-if="userRole.level=='国家级'" link type="primary" size="small" @click="editReport(scope.row)">修改</el-button>
              <el-button v-if="userRole.level!='国家级'"  link type="primary" size="small" @click="getEdit(scope.row,'second')">文件上传</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <div class="pagination-box">
        <el-pagination
      :total="totals"
      layout="prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange" 
    />
      </div>
    </div>
    <div class="showBox" v-if="showSuccess">
      <img src="../../assets/images/Check-Circle-Fill.png" alt="">
      <span>填报成功</span>
    </div>
  </template>
<script lang="ts" setup>
import countryFile from '@/components/countryFile.vue';
import { ref, onMounted } from 'vue'
import { reportFindList,reportExport ,reportpublish} from "@/util/api";
import { useRouter } from "vue-router";
import { ElMessage} from 'element-plus'
import { useStore } from '@/store'
const userRole = useStore().state.userInfo
//路由
const router = useRouter();
//修改报表id
const reportItem:any =ref({}) 
//报表请求参数
const form: any =ref({
            checkUserId:'',
            createUserId:'',
            developArea:'',
            rState:'1',
            reportTimeEnd:'',
            reportTimeStart:'',
            state:'1',
            templateType:'',
            val:'',
            currentPage: 1, //第几页
            pageNum: 10, //一页几个
      }) 

//总条数   
const totals:any = ref(0)
//报表数据     
const tableData:any = ref([])         
//等待
const loading:any = ref(false)
//上报成功展示      
const showSuccess: any = ref(false) 
const downReports = (item:any)=>{
  if(item.file==null)return ElMessage.error('无报表')
  let  flieitem = JSON.parse(item.file)[0]
  // console.log(flieitem)
  let link = document.createElement('a')
    link.style.display = 'none';
    link.href = '/api/file/show/'+flieitem.saveName;
    link.download = flieitem.showName;
    link.click()
    window.URL.revokeObjectURL(link.href)
} 
//获取报表数据
const getTable = async () => {
    loading.value=true
    const res: any = await reportFindList(form.value);
    // console.log(res.data.content)
  if (res.code == 200) {
    tableData.value = res.data.content;
    totals.value = parseInt(res.data.totalElements);
    loading.value=false
  }
};

//分页
const handleSizeChange = (val: number) => {
  //   console.log(`${val} items per page`)
  form.value.pageNum = val;
  getTable();
};
const handleCurrentChange = (val: number) => {
  //   console.log(`current page: ${val}`)
  form.value.currentPage = val;
  getTable();
};
//编辑
const getEdit = (item: any,tabs:any) => {
  let url=null
  if(item.templateId=='5'){
    url=  router.resolve({
    path: '/dominantCheck',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
    })
  }else if(item.templateId=='4'){
    url=  router.resolve({
    path: '/fourCheck',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs,
    }
  })}else if(item.templateId=='100'){
    url= router.resolve({
    path: '/summary',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }else if(item.templateId=='101'){
    url= router.resolve({
    path: '/staging',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }else if(item.templateId=='102'){
    url= router.resolve({
    path: '/poor',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }else{
    url=  router.resolve({
    path: '/check',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }
  window.open(url.href);
}
//修改国家级报表
const editReport=(e:any)=>{
  reportItem.value = e
    console.log(reportItem.value)
}
//上报
const getReport=async (item:any)=>{
    if(userRole.level=='国家级'&&item.file==null) return ElMessage.error('请先上传文件')
    if(item.filesQ==null)return ElMessage.error('请先上传文件')
    let res:any=await reportpublish(item.id)
    if(res){
    showSuccess.value = true
    getTable();
    setTimeout(() => {
      showSuccess.value = false
    }, 1500);
    }  
}

//导出
const downReport = (val: any) => {
    let name = val.name
    reportExport(val.id).then((res: any) => {
      let fileName = name + ".xlsx"
      handleFileError(res, fileName)
    })
  }
  const handleFileError = (res: any, fileName: any) => {
  if (typeof res.data !== 'undefined') {
    if (res.data.type === 'application/json') {
      const reader = new FileReader();
      reader.onload = function () {
      };
      reader.readAsText(new Blob([res.data]));
    }
  } else {
    var downloadUrl = window.URL.createObjectURL(new Blob([res]));
    var a = document.createElement('a');
    a.style.display = 'none';
    a.href = downloadUrl;
    a.download = fileName;
    var event = new MouseEvent('click');
    a.dispatchEvent(event);
  }
}

onMounted(()=>{
    getTable()
})
//动态添加table背景
const tableRowClassName = ({
  row,
  rowIndex,
}) => {
  if(row.notice){
    return 'warning-row'
  }
}
</script>
<style>
  .el-table .warning-row {
  --el-table-tr-bg-color: rgba(235, 76, 64, 0.1);
}
</style>
<style lang="scss" scoped>
.showBox {
  width: 326px;
  height: 208px;
  position: fixed;
  background-color: white;
  box-shadow: 0px 3px 29px 10px #D9D9D9;
  left: calc(50% - 163px);
  top: calc(50% - 104px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  font-weight: 500;
  z-index: 9999;

  img {
    display: block;
    width: 70px;
    height: 70px;
  }
}
.pagination-box{
      width: 90%;
      margin: 30px auto;
      ::v-deep(.el-pagination){
        float: right;
      }  
}
.down-bth{
  width: 90%;
  margin: 20px auto;
}
.data-check{
  display: flex;
}
</style>